package com.monna.util;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.monna.datebase.DBOpenHelper;
import com.monna.entity.Score;

import java.util.ArrayList;
import java.util.List;

/**
 * 处理用户分值：最高分、积分排行榜
 * @author 廖梦青
 */
public class ScoreUtil {

    private DBOpenHelper dbOpenHelper;
    private SQLiteDatabase database;

    /**
     * 初始化数据库
     * @param context
     */
    public ScoreUtil(Context context) {
        dbOpenHelper = new DBOpenHelper(context);
        database = dbOpenHelper.getReadableDatabase();
    }

    /**
     * 修改用户最高分
     * @param account
     * @param score
     */
    public void userHeightScore(String account, int score){
        String sql="update score set height_score =? where account =?";
        database.execSQL(sql, new Object[]{score, account});
    }

    /**
     * 获取游戏排行榜
     * @return
     */
    public ArrayList<Score> gamesLeaderboard(){
        ArrayList<Score> list = new ArrayList<>();
        String sql = "select account, height_score from score order by height_score desc";
        Cursor cursor = database.rawQuery(sql, null);
        while (cursor.moveToNext()){
            String account = cursor.getString(cursor.getColumnIndexOrThrow("account"));
            int heightScore = Integer.parseInt(cursor.getString(cursor.getColumnIndexOrThrow("height_score")));
            Score score = new Score(account, heightScore);
            list.add(score);
        }
        cursor.close();
        return list;
    }

    /**
     * 获取用户最高分
     * @param account
     * @return
     */
    public int getUserHeightScore(String account){
        int heirhtScore = 0;
        String sql = "select height_score from score where account =?";
        Cursor cursor = database.rawQuery(sql, new String[]{account});
        if (cursor.moveToFirst() == true){
            heirhtScore = cursor.getInt(cursor.getColumnIndexOrThrow("height_score"));
        }
        cursor.close();
        return heirhtScore;
    }

}
